package view.dlct.loaibc.backing;

import java.sql.SQLException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UISelectItems;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.RichDialog;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.adf.view.rich.component.rich.input.RichSelectOrderShuttle;
import oracle.adf.view.rich.event.DialogEvent;
import oracle.adf.view.rich.event.PopupCanceledEvent;

import oracle.jbo.Key;
import oracle.jbo.NameValuePairs;
import oracle.jbo.Row;
import oracle.jbo.domain.DBSequence;
import oracle.jbo.domain.Number;

import view.common.Utils;
import view.common.search.AdvancedSearchGroup;
import view.common.search.AdvancedSearchItem;

public class DmLoaiBcBean {
    private RichPopup popupUpdate;
    private RichDialog dialogUpdate;
    private RichPopup popupDelete;
    private RichSelectOrderShuttle selectNgonNgu;
    private RichSelectOrderShuttle selectTruongTt;

    public DmLoaiBcBean() {
    }

    public void beforePhase(PhaseEvent phaseEvent) {
        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            resetForm();
            rollback(null);
        }
    }

    private void resetForm() {
        Utils.search("DlctLoaiBaoCaoView1Iterator", new ArrayList());
    }

    public void showPopupThemMoi(ActionEvent actionEvent) {
        List<AdvancedSearchGroup> listASG = new ArrayList();
        AdvancedSearchGroup asg = new AdvancedSearchGroup();
        listASG.add(asg);
        AdvancedSearchItem asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("TrangThai");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        Utils.searchadvanced("DlctNgonNguView1Iterator", listASG);

        List<SelectItem> listSelectItem = new ArrayList();
        DCIteratorBinding ngonNguIterator =
            Utils.getIteratorBinding("DlctNgonNguView1Iterator");
        ngonNguIterator.setRangeSize(-1);
        Row[] rows = ngonNguIterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        for (int i = 0; i < rows.length; i++) {
            String id = ((DBSequence)rows[i].getAttribute("Id")).toString();
            String ma = (String)rows[i].getAttribute("Ma");
            String ten = (String)rows[i].getAttribute("Ten");
            SelectItem si = new SelectItem();
            si.setValue(id);
            si.setLabel(ma + "_" + ten);
            listSelectItem.add(si);
        }
        UISelectItems uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectNgonNgu.setValue(null);
        selectNgonNgu.getChildren().clear();
        selectNgonNgu.getChildren().add(uiSelectItems);

        uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(new ArrayList());
        selectTruongTt.setValue(null);
        selectTruongTt.getChildren().clear();
        selectTruongTt.getChildren().add(uiSelectItems);

        dialogUpdate.setTitle((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].THEM_MOI}"));
        dialogUpdate.setAffirmativeTextAndAccessKey((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].THEM_MOI}"));
        DCIteratorBinding loaiBaoCaoView1Iterator =
            Utils.getIteratorBinding("DlctLoaiBaoCaoView1Iterator");
        Row row =
            loaiBaoCaoView1Iterator.getViewObject().createAndInitRow(new NameValuePairs());
        loaiBaoCaoView1Iterator.executeQuery();
        loaiBaoCaoView1Iterator.setCurrentRowWithKey(row.getKey().toStringFormat(false));
        Utils.showPopup(popupUpdate);
    }

    public void showPopupSua(ActionEvent actionEvent) {
        DCIteratorBinding loaiBaoCaoView1Iterator =
            Utils.getIteratorBinding("DlctLoaiBaoCaoView1Iterator");
        if(loaiBaoCaoView1Iterator.getCurrentRow()!=null){
        List<AdvancedSearchGroup> listASG = new ArrayList();
        AdvancedSearchGroup asg = new AdvancedSearchGroup();
        listASG.add(asg);
        AdvancedSearchItem asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("TrangThai");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        Utils.searchadvanced("DlctNgonNguView1Iterator", listASG);
        List<SelectItem> listSelectItem = new ArrayList();
        DCIteratorBinding ngonNguIterator =
            Utils.getIteratorBinding("DlctNgonNguView1Iterator");
        ngonNguIterator.setRangeSize(-1);
        Row[] rows = ngonNguIterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        for (int i = 0; i < rows.length; i++) {
            String id = ((DBSequence)rows[i].getAttribute("Id")).toString();
            String ma = (String)rows[i].getAttribute("Ma");
            String ten = (String)rows[i].getAttribute("Ten");
            SelectItem si = new SelectItem();
            si.setValue(id);
            si.setLabel(ma + "_" + ten);
            listSelectItem.add(si);
        }
        UISelectItems uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectNgonNgu.getChildren().clear();
        selectNgonNgu.getChildren().add(uiSelectItems);

        DCIteratorBinding lbcNnView1Iterator =
            Utils.getIteratorBinding("DlctLbcNnView1Iterator");
        lbcNnView1Iterator.setRangeSize(-1);
        rows = lbcNnView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        List<String> listSelected = new ArrayList();
        listASG = new ArrayList();
        asg = new AdvancedSearchGroup();
        listASG.add(asg);
        asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("DlctLoaiTruongTt");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_LOAI_TRUONG_TT.BAO_CAO.getId()));
        asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("TrangThai");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));

        asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setOperator(AdvancedSearchItem.OPER_IN);
        asi.setItemName("DlctNgonNguId");
        asi.setRequired(true);
        for (int i = 0; i < rows.length; i++) {
            Number idNumber = (Number)rows[i].getAttribute("DlctNgonNguId");
            String idString = idNumber.toString();
            listSelected.add(idString);
            asi.getListValue().add(i, idNumber);
        }
        selectNgonNgu.setValue(listSelected);

        Utils.searchadvanced("DlctTruongTtView1Iterator", listASG);

        listSelectItem = new ArrayList();
        DCIteratorBinding truongTtIterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        truongTtIterator.setRangeSize(-1);
        rows = truongTtIterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        for (int i = 0; i < rows.length; i++) {
            String id = ((DBSequence)rows[i].getAttribute("Id")).toString();
            String ten = (String)rows[i].getAttribute("TenTruong");
            SelectItem si = new SelectItem();
            si.setValue(id);
            si.setLabel(ten);
            listSelectItem.add(si);
        }
        uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectTruongTt.getChildren().clear();
        selectTruongTt.getChildren().add(uiSelectItems);


        DCIteratorBinding lbcTtView1Iterator =
            Utils.getIteratorBinding("DlctLbcTtView1Iterator");
        lbcTtView1Iterator.setRangeSize(-1);
        rows = lbcTtView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        listSelected = new ArrayList();
        for (int i = 0; i < rows.length; i++) {
            Number idNumber = (Number)rows[i].getAttribute("DlctTruongTtId");
            String idString = idNumber.toString();
            listSelected.add(idString);
        }
        selectTruongTt.setValue(listSelected);
        dialogUpdate.setTitle((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].CAP_NHAT}"));
        dialogUpdate.setAffirmativeTextAndAccessKey((String)Utils.getElExpression("#{adfBundle['view.ViewControllerBundle'].CAP_NHAT}"));
        Utils.showPopup(popupUpdate);
        }else{
            String errorString =
                Utils.getResourceBundle("CHON_BAN_GHI_DE_THAO_TAC");
            FacesContext.getCurrentInstance().addMessage(null,
                                                         new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                          errorString,
                                                                          errorString));
        }
    }

    public void showPopupXoa(ActionEvent actionEvent) {
        DCIteratorBinding loaiBaoCaoView1Iterator =
            Utils.getIteratorBinding("DlctLoaiBaoCaoView1Iterator");
        if(loaiBaoCaoView1Iterator.getCurrentRow()!=null){
        Utils.showPopup(popupDelete);
        }else{
            String errorString =
                Utils.getResourceBundle("CHON_BAN_GHI_DE_THAO_TAC");
            FacesContext.getCurrentInstance().addMessage(null,
                                                         new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                          errorString,
                                                                          errorString));
        }
    }

    public void rollback(PopupCanceledEvent popupCanceledEvent) {
        DCIteratorBinding loaiBaoCaoView1Iterator =
            Utils.getIteratorBinding("DlctLoaiBaoCaoView1Iterator");
        loaiBaoCaoView1Iterator.getDataControl().getApplicationModule().getTransaction().rollback();
        String rowKey = null;
        if (loaiBaoCaoView1Iterator.getCurrentRow() != null)
            rowKey =
                    loaiBaoCaoView1Iterator.getCurrentRow().getKey().toStringFormat(false);
        loaiBaoCaoView1Iterator.executeQuery();
        if (rowKey != null)
            loaiBaoCaoView1Iterator.setCurrentRowWithKey(rowKey);
    }

    public void commit(DialogEvent dialogEvent) {
        DCIteratorBinding lbcNnView1Iterator =
            Utils.getIteratorBinding("DlctLbcNnView1Iterator");
        DCIteratorBinding lbcTtView1Iterator =
            Utils.getIteratorBinding("DlctLbcTtView1Iterator");
        lbcTtView1Iterator.setRangeSize(-1);
        Row[] rows = lbcTtView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        List<String> listDelete = new ArrayList();
        for (int i = 0; i < rows.length; i++) {
            Key key = rows[i].getKey();
            listDelete.add(key.toStringFormat(false));
        }
        for (String key : listDelete) {
            lbcTtView1Iterator.removeRowWithKey(key);
        }
        lbcNnView1Iterator.setRangeSize(-1);
        rows = lbcNnView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        listDelete = new ArrayList();
        for (int i = 0; i < rows.length; i++) {
            Key key = rows[i].getKey();
            listDelete.add(key.toStringFormat(false));
        }
        for (String key : listDelete) {
            lbcNnView1Iterator.removeRowWithKey(key);
        }
        List<String> listSelected = (List<String>)selectNgonNgu.getValue();
        for (String idString : listSelected) {
            Number idNumber = null;
            try {
                idNumber = new Number(idString);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (idNumber != null) {
                Row row = lbcNnView1Iterator.getViewObject().createRow();
                row.setAttribute("DlctNgonNguId", idNumber);
            }
        }
        listSelected = (List<String>)selectTruongTt.getValue();
        Number thuTu = new Number(1);
        for (String idString : listSelected) {
            Number idNumber = null;
            try {
                idNumber = new Number(idString);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (idNumber != null) {
                thuTu = thuTu.add(1);
                Row row = lbcTtView1Iterator.getViewObject().createRow();
                row.setAttribute("DlctTruongTtId", idNumber);
            }
        }

        DCIteratorBinding loaiBaoCaoView1Iterator =
            Utils.getIteratorBinding("DlctLoaiBaoCaoView1Iterator");
        List<String> listTruongTt = new ArrayList();
        listTruongTt.add("Ten");
        for (String tenField : listTruongTt) {
            String value =
                (String)loaiBaoCaoView1Iterator.getCurrentRow().getAttribute(tenField);
            if (value != null) {
                loaiBaoCaoView1Iterator.getCurrentRow().setAttribute(tenField,
                                                                   value.trim());
            }
        }
        loaiBaoCaoView1Iterator.getDataControl().getApplicationModule().getTransaction().commit();
        String rowKey =
            loaiBaoCaoView1Iterator.getCurrentRow().getKey().toStringFormat(false);
        loaiBaoCaoView1Iterator.executeQuery();
        loaiBaoCaoView1Iterator.setCurrentRowWithKey(rowKey);
    }

    public void delete(DialogEvent dialogEvent) {
        try{
        DCIteratorBinding lbcNnView1Iterator =
            Utils.getIteratorBinding("DlctLbcNnView1Iterator");
        DCIteratorBinding lbcTtView1Iterator =
            Utils.getIteratorBinding("DlctLbcTtView1Iterator");
        lbcTtView1Iterator.setRangeSize(-1);
        Row[] rows = lbcTtView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        List<String> listDelete = new ArrayList();
        for (int i = 0; i < rows.length; i++) {
            Key key = rows[i].getKey();
            listDelete.add(key.toStringFormat(false));
        }
        for (String key : listDelete) {
            lbcTtView1Iterator.removeRowWithKey(key);
        }
        lbcNnView1Iterator.setRangeSize(-1);
        rows = lbcNnView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        listDelete = new ArrayList();
        for (int i = 0; i < rows.length; i++) {
            Key key = rows[i].getKey();
            listDelete.add(key.toStringFormat(false));
        }
        for (String key : listDelete) {
            lbcNnView1Iterator.removeRowWithKey(key);
        }
        DCIteratorBinding loaiBaoCaoView1Iterator =
            Utils.getIteratorBinding("DlctLoaiBaoCaoView1Iterator");
        loaiBaoCaoView1Iterator.removeCurrentRow();
        loaiBaoCaoView1Iterator.getDataControl().getApplicationModule().getTransaction().commit();
        loaiBaoCaoView1Iterator.executeQuery();
        }catch(Exception e){
            String errorString =
                Utils.getResourceBundle("CON_BAN_GHI_LIEN_QUAN");
            FacesContext.getCurrentInstance().addMessage(dialogEvent.getComponent().getClientId(FacesContext.getCurrentInstance()),
                                                         new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                          errorString,
                                                                          errorString));
            e.printStackTrace();
        }
    }

    public void changeNgonNgu(ValueChangeEvent valueChangeEvent) {
        List<String> ngonNguIds = (List<String>)valueChangeEvent.getNewValue();
        List<AdvancedSearchGroup> listASG = new ArrayList();
        AdvancedSearchGroup asg = new AdvancedSearchGroup();
        listASG.add(asg);
        AdvancedSearchItem asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("TrangThai");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        asi = new AdvancedSearchItem();
        asg.getListChildren().add(asi);
        asi.setItemName("DlctLoaiTruongTt");
        asi.setRequired(true);
        asi.getListValue().add(0,
                               new Number(Utils.ENUM_LOAI_TRUONG_TT.BAO_CAO.getId()));

        if (ngonNguIds != null) {
            asi = new AdvancedSearchItem();
            asg.getListChildren().add(asi);
            asi.setOperator(AdvancedSearchItem.OPER_IN);
            asi.setItemName("DlctNgonNguId");
            asi.setRequired(true);
            int count = 0;
            for (String ngonNguId : ngonNguIds) {
                Number idNumber = null;
                try {
                    idNumber = new Number(ngonNguId);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                if (idNumber != null) {
                    asi.getListValue().add(count++, idNumber);
                }
            }
        }

        Utils.searchadvanced("DlctTruongTtView1Iterator", listASG);

        List<SelectItem> listSelectItem = new ArrayList();
        DCIteratorBinding truongTtIterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        truongTtIterator.setRangeSize(-1);
        Row[] rows = truongTtIterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }
        for (int i = 0; i < rows.length; i++) {
            String id = ((DBSequence)rows[i].getAttribute("Id")).toString();
            String ten = (String)rows[i].getAttribute("TenTruong");
            SelectItem si = new SelectItem();
            si.setValue(id);
            si.setLabel(ten);
            listSelectItem.add(si);
        }
        UISelectItems uiSelectItems = new UISelectItems();
        uiSelectItems.setValue(listSelectItem);
        selectTruongTt.getChildren().clear();
        selectTruongTt.getChildren().add(uiSelectItems);
    }

    public void setPopupUpdate(RichPopup popupUpdate) {
        this.popupUpdate = popupUpdate;
    }

    public RichPopup getPopupUpdate() {
        return popupUpdate;
    }

    public void setDialogUpdate(RichDialog dialogUpdate) {
        this.dialogUpdate = dialogUpdate;
    }

    public RichDialog getDialogUpdate() {
        return dialogUpdate;
    }

    public void setPopupDelete(RichPopup popupDelete) {
        this.popupDelete = popupDelete;
    }

    public RichPopup getPopupDelete() {
        return popupDelete;
    }

    public void setSelectNgonNgu(RichSelectOrderShuttle selectNgonNgu) {
        this.selectNgonNgu = selectNgonNgu;
    }

    public RichSelectOrderShuttle getSelectNgonNgu() {
        return selectNgonNgu;
    }

    public void setSelectTruongTt(RichSelectOrderShuttle selectTruongTt) {
        this.selectTruongTt = selectTruongTt;
    }

    public RichSelectOrderShuttle getSelectTruongTt() {
        return selectTruongTt;
    }
}
